//
//  CorgiUserAccountViewModel.swift
//  weibo
//
//  Created by Corgi on 17/3/23.
//  Copyright © 2017年 cocoaHangTou. All rights reserved.
//

import UIKit

private let userAccount_Path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("account.plist")

/*
封装网络请求
数据缓存
处理数据相关逻辑
*/
class CorgiUserAccountViewModel: NSObject {
    
    static let shared: CorgiUserAccountViewModel = CorgiUserAccountViewModel()
    
    private override init() {
        super.init()
        
        self.account = self.loadUserAccount()
    }
    
    var account: CorgiUserAccountModel?
    
    var accountToken: String? {
    
        if userLogin {
        
            return account?.access_token
            
        }
        
        return nil
    }
    
    var iconURL: URL? {
    
        return URL(string: account?.avatar_large ?? "")
        
    }
    
    var isExpires: Bool {
    
        if account?.expires_date?.compare(Date()) == .orderedDescending {
        
            return false
        
        }
        
        return true
    }
    
    var userLogin: Bool {
    
        if account?.access_token != nil && !isExpires {
        
            return true
            
        }
        
        return false
    }
    
    ///token请求,获得令牌
    func loadAccessToken(code: String, finished: @escaping (Bool) -> ()) {
        
        //token url
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let para = ["client_id" : client_id,
                    "client_secret" : client_secret,
                    "grant_type" : "authorization_code",
                    "code" : code,
                    "redirect_uri" : redirect_uri]
        
        //发送网络请求,获取token
        HMNetworkTools.shared.request(method: .POST, urlString: urlString, paramters: para) { (result, error) in
            
            if error != nil {
                
//                SVProgressHUD.showError(withStatus: "网络错误")
                finished(false)
                
                return
            }
            
            //获取token成功,发送网络请求,获取用户信息
            self.loadUserInfo(result as! [String : Any], loadUserInfoFinished: finished)
            
        }
    }
    
    private func loadUserInfo(_ dict: [String : Any], loadUserInfoFinished: @escaping (Bool) -> ()) {
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        let token = dict["access_token"]
        
        let uid = dict["uid"]
        
        let para = ["access_token" : token,
                    "uid" : uid]
        
        //发送网络请求
        HMNetworkTools.shared.request(method: .GET, urlString: urlString, paramters: para) { (result, error) in
            
            if error != nil {
                
//                SVProgressHUD.showError(withStatus: "网络错误")
                
                loadUserInfoFinished(false)
                
                return
            }
            
            var userInfoDict = result as! [String : Any]
            
            //遍历dict,与userInfoDict合并
            for (key, value) in dict {
                
                userInfoDict[key] = value
                
            }
            
            //字典转模型
            let userAccountModel = CorgiUserAccountModel(dict: userInfoDict)
            
            //归档
            self.saveUserAccount(userAccount: userAccountModel)
            
            self.account = userAccountModel
            
            loadUserInfoFinished(true)
        }
    }
    
    ///归档方法封装
    private func saveUserAccount(userAccount: CorgiUserAccountModel) {
        
        NSKeyedArchiver.archiveRootObject(userAccount, toFile: userAccount_Path)
        
        
    }
    
    ///解档方法封装
    func loadUserAccount() -> CorgiUserAccountModel? {
        
        let account = NSKeyedUnarchiver.unarchiveObject(withFile: userAccount_Path)
        
        if let acc = account as? CorgiUserAccountModel {
        
            return acc
        
        }
        
        return nil
    }
    
}
